#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File    :   pub_sub.py
@Time    :   2024-07-09 13:02:26
@Author  :   chakcy 
@Email   :   947105045@qq.com
@description   :   redis pub/sub 工具类
'''

from redis.asyncio import Redis

class PubSub:
    def __init__(self, redis: Redis):
        # 初始化 Redis 连接
        self.redis = redis
        self.pubsub = redis.pubsub() 
    async def subscribe(self, channel: str):
        """订阅指定频道"""
        await self.pubsub.subscribe(channel) 
        return self.pubsub
    async def publish(self, channel: str, message: str): 
        """发布消息到指定频道"""
        return await self.redis.publish(channel, message) 
    async def get_message(self): 
        """获取消息"""
        return await self.pubsub.get_message(ignore_subscribe_messages=True) 
    async def unsubscribe(self, channel: str):
        """取消订阅指定频道"""
        await self.pubsub.unsubscribe(channel) 
    async def close(self):
        """关闭 PubSub 连接"""
        await self.pubsub.close()